// miniprogram/page/index/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {}
  },

  getCreateUserInfo(e) {
    let that = this
    let wxInfo = e.detail.userInfo
    const db = wx.cloud.database()
    // 登录
    wx.showLoading()
    db.collection('lspUser').get({
      data: {
        _openid: wxInfo.openId
      },
      success: function (res) {
        let data = res.data
        if (data.length > 0) {
          that.setData({
            userInfo: res.data[0]
          })
          wx.setStorageSync('user_id', res.data[0]._id)
          wx.hideLoading()
          wx.showToast({
            title: '登录成功',
            icon: 'none',
            duration: 2000
          })
        } else {
          // 注册用户
          const date = new Date()
          let userInfo = {
            nickName: wxInfo.nickName || '萌新',
            headPic: wxInfo.avatarUrl,
            level: 1,
            createTime: `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours() < 10 ? '0' + date.getHours() : date.getHours()}:${date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()}:${date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()}`,
            _openid: wxInfo.openId,
          }
          db.collection('lspUser').add({
            data: userInfo,
            success: function (res) {
              userInfo._id = res._id
              that.setData({ userInfo })
              wx.setStorageSync('user_id', res._id)
              wx.hideLoading()
              wx.showToast({
                title: '注册成功',
                icon: 'none',
                duration: 2000
              })

            }
          })
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    let _id = app.globalData.user_id
    if (_id) {
      const db = wx.cloud.database()
      db.collection('lspUser').get({
        data: { _id },
        success: function (res) {
          that.setData({
            userInfo: res.data[0]
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})